package gr.unipi.cinema;

import java.sql.*;
import java.util.ArrayList;

public class Theater {
	
	public static TheaterData[] getTheaterData(int id, String qStr) {
		TheaterData[] res = null;
		Connection connection = SqlConnection.getConnection();
		if (connection == null) {
			System.out.println("Cloud not connect to db");
			return res;
		}
		
		Statement st = null;
		ResultSet resultSet = null;
		
		try {
			st = connection.createStatement();
			
			String sql =
					"SELECT ID, THEATERTITLE, PHYSADDR, PHONENUM, EMAILADDR, IMAGEURL " +
					"FROM CTHEATER " +
					"WHERE (ISACTIVE = 1) ";
			
			if (id != 0) {
				sql = sql + "AND (ID = " + id + ") ";
			}
			
			if ((qStr != null) && (qStr.length() > 0)) {
				sql = sql + "AND ( (THEATERTITLE LIKE '%" + qStr + "%') OR (PHYSADDR LIKE '%" + qStr +"%') ) ";
			}
			
			System.out.println("Executing query: " + sql);
			
			resultSet = st.executeQuery(sql);
			
			ArrayList<TheaterData> thList = new ArrayList<>(5);
			TheaterData entry = null;
			
			while (resultSet.next()) {
				entry = new TheaterData(resultSet.getInt("ID"),
										resultSet.getString("THEATERTITLE"),
										resultSet.getString("PHYSADDR"),
										resultSet.getString("PHONENUM"),
										resultSet.getString("EMAILADDR"),
										resultSet.getString("IMAGEURL"));

				thList.add(entry);
			}
			
			res = thList.toArray(new TheaterData[0]);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
				resultSet = null;
			}
			
			if (st != null) {
				try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				st = null;
			}
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connection = null;
		}
		
		return res;
	}
}
